package com.xexun.gpstracker.ui;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import com.xexun.gpstracker.MainActivity;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.fix.grant.PermissionsManager;
import com.xexun.gpstracker.fix.grant.PermissionsResultAction;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.listener.PrettyTextChangeListener;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.pojo.User;
import com.xexun.gpstracker.qrcode.CaptureActivity;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.IMEI;
import com.xexun.gpstracker.util.JSONHelper;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.vo.Session;

/**
 * 用户注册页面
 *
 * @author huangfei
 */
public class RegistActivity extends Activity implements OnClickListener {

    @ViewInject(R.id.watch_region)
    private Spinner watchRegion;//手表使用区域

    private ImageButton backButton;
    private Button registButton, validButton;
    private EditText phoneText, pwdText, pwdConfirmText, validText, deviceET, userNameConfirm;
    //    private TimeCount timeCount;
    private TextView nofityView, protocolView;    //错误提示
    private boolean isValid = false;    //验证号码是否可用
    private LinearLayout protocolLayout, registLL;
    private ArrayAdapter<String> watchRegionAdapter;
    private ArrayAdapter relationAdapter;

    @ViewInject(R.id.relation)
    private Spinner relation;

    @ViewInject(R.id.watchPhone)
    private EditText watchPhone;

    @ViewInject(R.id.localTimezone)
    private Spinner localTimezone;

    @ViewInject(R.id.localTimezoneTitle)
    private LinearLayout localTimezoneTitle;

    @ViewInject(R.id.localTimezoneField)
    private RelativeLayout localTimezoneField;

    private List<String> relationIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        x.view().inject(this);
//        timeCount = new TimeCount(Constants.VALIDCODE_TOTAL_TIME, Constants.VALIDCODE_APART_TIME);

        backButton = (ImageButton) findViewById(R.id.backBtn);
        registButton = (Button) findViewById(R.id.registBtn);
//        validButton = (Button) findViewById(R.id.validBtn);
        phoneText = (EditText) findViewById(R.id.phoneET);
        pwdText = (EditText) findViewById(R.id.pwdET);
        pwdConfirmText = (EditText) findViewById(R.id.pwdConfirmET);
        validText = (EditText) findViewById(R.id.validET);
        protocolView = (TextView) findViewById(R.id.protocolTV);
        protocolView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        protocolLayout = (LinearLayout) findViewById(R.id.protocolLayout);
        deviceET = (EditText) findViewById(R.id.imeiET);
        userNameConfirm = (EditText) findViewById(R.id.userNameConfirm);
        registLL = (LinearLayout) findViewById(R.id.registLL);
        if (Constants.IS_CHINA_VERSION) {
            ImageView imageView=(ImageView)findViewById(R.id.logoIV);
            imageView.setImageResource(R.drawable.logo_normal);
        }

        backButton.setOnClickListener(this);
        registButton.setOnClickListener(this);
//        validButton.setOnClickListener(this);
        protocolView.setOnClickListener(this);
        registLL.setOnClickListener(this);
        findViewById(R.id.scanBtn).setOnClickListener(this);

        PrettyTextChangeListener pListener = new PrettyTextChangeListener(3, 4);
        phoneText.addTextChangedListener(pListener);
        userNameConfirm.addTextChangedListener(pListener);
        watchPhone.addTextChangedListener(pListener);
        deviceET.addTextChangedListener(new PrettyTextChangeListener(4));

        relationAdapter = ArrayAdapter.createFromResource(this, R.array.relation_family, R.layout.item_spinner_adduser);
        relationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        relation.setAdapter(relationAdapter);
        relation.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Utils.hideInputBoard(RegistActivity.this, v);
                checkAccountConfirm();
                return false;
            }
        });
        relationIds = Arrays.asList(getResources().getStringArray(R.array.relation_family_id));

        List<String> timeZoneIds = Utils.genTimezones();
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.spinner_item, timeZoneIds);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        localTimezone.setAdapter(adapter);
        float offset = TimeZone.getDefault().getRawOffset() / 1000f / 60 / 60;
        localTimezone.setSelection(adapter.getPosition(Utils.formatTimezoneOffset(offset)), true);
        if (Constants.CHINA.equals(Locale.getDefault().toString())) {
            localTimezoneTitle.setVisibility(View.GONE);
            localTimezoneField.setVisibility(View.GONE);
        }

        String[] regions = new String[]{getString(R.string.pl_select), getString(R.string.china), getString(R.string.not_china)};
        watchRegionAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, regions);
        watchRegionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        watchRegion.setAdapter(watchRegionAdapter);
        watchRegion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position > 0) {
                    CommUtil.showMsgShort(getString(R.string.watch_region_select_note));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        watchRegion.setSelection(1);
        watchRegion.setEnabled(false);

        CheckAccountListener listener = new CheckAccountListener();
        userNameConfirm.setOnFocusChangeListener(listener);
        watchPhone.setOnFocusChangeListener(listener);
        deviceET.setOnFocusChangeListener(listener);
        validText.setOnFocusChangeListener(listener);
        pwdText.setOnFocusChangeListener(listener);
        pwdConfirmText.setOnFocusChangeListener(listener);
    }

    private boolean checkAccountConfirm() {
        if (CommUtil.isBlank(userNameConfirm.getText()) || !phoneText.getText().toString().equals(userNameConfirm.getText().toString())) {
            CommUtil.showMsgShort(getString(R.string.name_confirm_error));
            return false;
        }
        return true;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.scanBtn:
                Intent openCameraIntent = new Intent(RegistActivity.this, CaptureActivity.class);
//                openCameraIntent.putExtra("type", "register");
                startActivityForResult(openCameraIntent, 0);
                break;
            case R.id.backBtn:
                RegistActivity.this.finish();
                break;
            case R.id.protocolTV:
                Intent pIntent = new Intent(RegistActivity.this, ProtocolActivity.class);
                RegistActivity.this.startActivity(pIntent);
                break;
            case R.id.registBtn:
                final String pwd = pwdText.getText().toString().trim();
                String pwdConfirm = pwdConfirmText.getText().toString().trim();
                final String validCode = validText.getText().toString().trim();
                final String phone = CommUtil.trimSeprator(phoneText.getText().toString().trim(), null);
                final String imei = CommUtil.trimSeprator(deviceET.getText().toString().trim(), null);
                final String nameConfirm = CommUtil.trimSeprator(userNameConfirm.getText().toString().trim(), null);
                final String wPhone = CommUtil.trimSeprator(watchPhone.getText().toString().trim(), null);
                final float localeTimezone = Utils.convertTimezoneToOffset(localTimezone.getSelectedItem().toString());
                final String rel = relationIds.get(1);//relation.getSelectedItemPosition());

                if (CommUtil.isBlank(phone)) {
                    Toast.makeText(RegistActivity.this, R.string.phone_no_hint, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Constants.IS_CHINA_VERSION && !Utils.isChinaMobileNO(phone)) {
                    CommUtil.showMsgShort(getString(R.string.not_china_mobile));
                    return;
                }
                if (!phone.equals(nameConfirm)) {
                    CommUtil.showMsgShort(getString(R.string.name_confirm_error));
                    return;
                }
//                if (relation.getSelectedItemPosition() == 0) {
//                    Toast.makeText(this, R.string.add_user_relation_null, Toast.LENGTH_SHORT).show();
//                    return;
//                }
                if (CommUtil.isBlank(wPhone)) {
                    CommUtil.showMsgShort(getString(R.string.watchPhoneHint));
                    return;
                }
                if (Constants.IS_CHINA_VERSION && !Utils.isChinaMobileNO(wPhone)) {
                    CommUtil.showMsgShort(getString(R.string.not_china_mobile));
                    return;
                }
                if (CommUtil.isBlank(imei) || imei.length() != 15) {
                    Toast.makeText(RegistActivity.this, R.string.add_device_scan, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (CommUtil.isBlank(validCode)) {
                    Toast.makeText(RegistActivity.this, R.string.valid_null_err, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (CommUtil.isBlank(pwd)) {
                    Toast.makeText(RegistActivity.this, R.string.pwd_null_err, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (pwd.length() < 6 || pwd.length() > 20) {
                    Toast.makeText(RegistActivity.this, R.string.pwd_length_err, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!pwdConfirm.equals(pwd)) {
                    Toast.makeText(RegistActivity.this, R.string.pwd_confirm_err, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (watchRegion.getSelectedItemPosition() < 1) {
                    Toast.makeText(this, getString(R.string.rel_watch_region_note), Toast.LENGTH_SHORT).show();
                    return;
                }
                PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(RegistActivity.this,
                        new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE},
                        new PermissionsResultAction() {
                            @Override
                            public void onGranted() {
                                if (CommUtil.isBlank(Session.getInstance().getClientId())) {
                                    List<String> clientIds = IMEI.getIMEI(RegistActivity.this);
                                    if (CommUtil.isNotEmpty(clientIds)) {
                                        Session.getInstance().setClientId(clientIds.get(0));
                                    }
                                }
                                regist(phone, pwd, validCode, imei, rel, wPhone, localeTimezone);
                            }

                            @Override
                            public void onDenied(String permission) {
                                CommUtil.showMsgShort(String.format(getString(R.string.permission_refuse_comm_note), getString(R.string.permission_refuse_call_phone_note)));
                            }
                        });
                break;
//            case R.id.validBtn:
//                //允许使用平台的用户名密码登录
////				if(phoneText.getText().toString().trim().length() != 11){
////					Toast.makeText(RegistActivity.this, "手机号格式不正确", Toast.LENGTH_SHORT).show();
////				}else{}
//
//                /*用户点击 获取验证码 进行号码校验*/
//                //获得用户输入的手机号码
//                String phoneNumber = phoneText.getText().toString().trim();
//                //进行校验
//                if (!Utils.isMobileNO(phoneNumber)) {
//                    Toast.makeText(RegistActivity.this, R.string.phone_err_, Toast.LENGTH_SHORT).show();
//                } else {
//                    checkPhoneAndRetrieveVaildCode(phoneNumber);
//                }
//                break;
            //case R.id.relation:
            case R.id.registLL:
                Utils.hideInputBoard(RegistActivity.this, view);
                break;
        }
    }


    /**
     * 校验手机号码是否已经被注册
     *
     * @param phoneNumber 用户输入的手机号
     * @return true 已经被注册  false 未被注册
     */
    private void checkPhoneAndRetrieveVaildCode(final String phoneNumber) {

        User.checkPhone(RegistActivity.this, phoneNumber, new HttpCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onSuccess(ResponseData obj) {
                if (obj.getRetcode() == 1) {
                    //用户存在
                    Toast.makeText(RegistActivity.this, R.string.phone_err_exist, Toast.LENGTH_SHORT).show();
                } else if (obj.getRetcode() == 3) {
                    //用户不存在
                    getValid(phoneNumber);
//                    timeCount.start();
                } else {
                    Toast.makeText(RegistActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String message) {
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                Utils.getManager(RegistActivity.this).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }


    /**
     * 获取验证码
     *
     * @param phoneStr
     */
    private void getValid(String phoneStr) {
        User.getValdcode(this, phoneStr, new HttpCallback() {
            @Override
            public void onStart() {
                WizardAlertDialog.getInstance().showProgressDialog(R.string.send_valid_code, RegistActivity.this);
            }

            @Override
            public void onFinish() {
                WizardAlertDialog.getInstance().closeProgressDialog();
            }

            @Override
            public void onSuccess(ResponseData obj) {
                Toast.makeText(RegistActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
                if (obj.getRetcode() == 0) {
//                    timeCount.cancel();
//                    timeCount.onFinish();
                }
            }

            @Override
            public void onFailure(String message) {
                Toast.makeText(RegistActivity.this, message, Toast.LENGTH_SHORT).show();
//                timeCount.cancel();
//                timeCount.onFinish();
            }
        });
    }

    /**
     * 注册
     *
     * @param phoneStr
     * @param pwdStr
     * @param validCode
     * @param imei
     * @param rel
     * @param wPhone
     * @param timezone
     */
    private void regist(final String phoneStr, String pwdStr, final String validCode, final String imei, String rel, String wPhone, float timezone) {
        User.register(this, phoneStr, pwdStr, validCode, imei, watchRegion.getSelectedItemPosition(), rel, wPhone, timezone, new HttpCallback() {
            @Override
            public void onStart() {
                WizardAlertDialog.getInstance().showProgressDialog(R.string.regist_post_data, RegistActivity.this);
            }

            @Override
            public void onFinish() {
                WizardAlertDialog.getInstance().closeProgressDialog();
            }

            @Override
            public void onSuccess(ResponseData obj) {
                if (obj.getRetcode() == 1) {
                    Session.getInstance().setAccessKey(JSONHelper.getString(obj.getBody(), "accesskey"));

                    User user = new User();
                    user.setPhone(phoneStr);
                    user.setAppUserNum(JSONHelper.getString(obj.getBody(), "appUserNum"));
                    user.setImei(JSONHelper.getString(obj.getBody(), "imei"));//用户IMEI
                    user.setId(JSONHelper.getLong(obj.getBody(), "id"));
                    Session.getInstance().setUser(user);
                    Session.getInstance().setImei(user.getImei());

                    Utils.showNotifyDialog(RegistActivity.this, R.string.note, R.string.regSucc, R.string.known, 0, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(RegistActivity.this, MainActivity.class);
                            intent.putExtra("imei", imei);//终端IMEI
                            intent.putExtra("validCode", validCode);
                            startActivity(intent);
                            finish();
                        }
                    }, null, 0, null);
                } else {
                    Toast.makeText(RegistActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String message) {
            }
        });
    }


    /* 定义一个倒计时的内部类 */
//    class TimeCount extends CountDownTimer {
//        public TimeCount(long millisInFuture, long countDownInterval) {
//            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
//        }
//
//        @Override
//        public void onFinish() {//计时完毕时触发
//            validButton.setText(R.string.get_valid_hint);
//            validButton.setClickable(true);
//        }
//
//        @Override
//        public void onTick(long millisUntilFinished) {//计时过程显示
//            validButton.setClickable(false);
//            validButton.setText(millisUntilFinished / 1000 + getResources().getString(R.string.time_minus_hint));
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            deviceET.setText(scanResult);
        }
    }

    private class CheckAccountListener implements View.OnFocusChangeListener {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (v == userNameConfirm && hasFocus || CommUtil.isBlank(userNameConfirm.getText())) {
                return;
            }
            if (hasFocus && !checkAccountConfirm()) {
                Utils.hideInputBoard(RegistActivity.this, v);
                Utils.showInputBoard(RegistActivity.this, userNameConfirm);
                userNameConfirm.setSelection(userNameConfirm.getText().length());
            }
        }
    }

    @Override
    protected void onDestroy() {
        /*退出注册页面时，更改注册标记为初始值*/
        super.onDestroy();
    }
}
